package net.hserver.hp_client.service;

import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;



import net.hserver.hp.client.CallMsg;
import net.hserver.hp.client.HpClient;
import net.hserver.hp_client.R;
import net.hserver.hp_client.config.ConstConfig;


import java.util.Timer;
import java.util.TimerTask;

import static net.hserver.hp_client.config.ConstConfig.PORT;

public class ProxyService extends Service {

    private String localIp;
    private String localPort;
    private String remotePort;
    private HpClient client;
    private Timer timer;

    //定义浮动窗口布局
    LinearLayout mFloatLayout;
    WindowManager.LayoutParams wmParams;
    //创建浮动窗口设置布局参数的对象
    WindowManager mWindowManager;

    ImageView mFloatView;

    private boolean longClick = false;


    private void openToast() {
        mFloatView.setImageResource(R.drawable.open);
    }

    private void closeToast() {
        mFloatView.setImageResource(R.drawable.close);
    }

    @SuppressLint({"ClickableViewAccessibility", "RtlHardcoded"})
    private void createFloatView() {
        wmParams = new WindowManager.LayoutParams();
        //获取WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(WINDOW_SERVICE);
        //设置window type
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }else {
            wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        wmParams.x = 0;
        wmParams.y = 200;
        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
//        wmParams.format = PixelFormat.TRANSPARENT;
        //获取浮动窗口视图所在布局
        mFloatLayout =(LinearLayout) LayoutInflater.from(getApplication()).inflate(R.layout.open, null);
        //添加mFloatLayout
        try {
            mWindowManager.addView(mFloatLayout, wmParams);
        }catch (Throwable e){
            e.printStackTrace();
        }
        //浮动窗口按钮
        mFloatView = mFloatLayout.findViewById(R.id.float_id);
        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        //设置监听浮动窗口的触摸移动
        mFloatView.setOnTouchListener((v, event) -> {
            if (longClick) {
                //getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
                wmParams.x = (int) event.getRawX() - mFloatView.getMeasuredWidth() / 2;
                //25为状态栏的高度
                wmParams.y = (int) event.getRawY() - mFloatView.getMeasuredHeight() / 2 - getStatusBarHeight();
                //刷新
                mWindowManager.updateViewLayout(mFloatLayout, wmParams);
            }
            return false;
        });
        mFloatView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(getApplicationContext(), "你可以移动了", Toast.LENGTH_SHORT).show();
                longClick = true;
                return false;
            }
        });
        mFloatView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ConstConfig.USER_VO != null) {
                    try {

                        if (client.getStatus()){
                            client.close();
                            openToast();
                        }else {
                            client.connect(ConstConfig.IP, PORT, ConstConfig.USER_VO.getUsername(), ConstConfig.USER_VO.getPassword(), Integer.parseInt(remotePort), localIp, Integer.parseInt(localPort));
                            openToast();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Toast.makeText(getApplicationContext(), "长按移动", Toast.LENGTH_SHORT).show();
                longClick = false;
            }
        });

    }

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    @Override
    public void onCreate() {
        Log.i("Kathy", "onCreate - Thread ID = " + Thread.currentThread().getId());
        client = new HpClient(new CallMsg() {
            @Override
            public void message(String s) {
                if (s == null) {
                    return;
                }
                if (s.contains("断开")) {
                    Message message=new Message();
                    message.what=-1;
                    handler.sendMessage(message);
                }
                Intent intent = new Intent();
                intent.setAction("com.xch.servicecallback.content");
                intent.putExtra("message", s);
                sendBroadcast(intent);
            }
        });

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (client.getStatus()) {
                    Message message=new Message();
                    message.what=1;
                    handler.sendMessage(message);
                } else {
                    Message message=new Message();
                    message.what=-1;
                    handler.sendMessage(message);
                }
                Intent intent = new Intent();
                intent.setAction("com.xch.servicecallback.content");
                intent.putExtra("status", String.valueOf(client.getStatus()));
                sendBroadcast(intent);
                Log.e("--", "---------");
            }
        }, 2000, 2000);

        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            createFloatView();
            localIp = intent.getStringExtra("localIp");
            localPort = intent.getStringExtra("localPort");
            remotePort = intent.getStringExtra("remotePort");
            if (ConstConfig.USER_VO != null) {
                try {
                    client.connect(ConstConfig.IP, PORT, ConstConfig.USER_VO.getUsername(), ConstConfig.USER_VO.getPassword(), Integer.parseInt(remotePort), localIp, Integer.parseInt(localPort));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }catch (Throwable e){}
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @SuppressLint("HandlerLeak")
    public final Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                openToast();
            } else if (msg.what == -1) {
                closeToast();
            }
            super.handleMessage(msg);
        }
    };



    @Override
    public void onDestroy() {

        if (mFloatLayout != null) {
            mWindowManager.removeView(mFloatLayout);
        }

        if (client != null) {
            client.close();
            client = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }

}